#include <stdio.h>
#include "pico/stdlib.h"
#include "pico/binary_info.h"
#include "hardware/spi.h"

#include "wizchip_conf.h"
#include "w5100s.h"
#include "bsp_spi.h"
#include "dhcp.h"   // Use dhcp
#include "socket.h" // Use socket
#include "UPnP.h"   // Use upnp

#define SOCKET_ID 0                      // Socket number
#define ETHERNET_BUF_MAX_SIZE (1024 * 4) // Send and receive cache size
#define DHCP_RETRY_COUNT 5               // DHCP retry times
#define USER_LED_PIN 25                  // Onboard led pin

/**
 * @brief   Timer callback processing function, used for dhcp timing processing
 * @param   repeating :Timer structure
 * @return  bool
 */
bool repeating_timer_callback(struct repeating_timer *t);

/**
 * @brief   Initialization of chip network information
 * @param   conf_info :Static configuration information
 * @return  none
 */
void network_init(wiz_NetInfo *conf_info);

/**--
 * @brief   Initiallization led and Registration function
 * @param   none
 * @return  none
 */
void UserLED_Init(void);

/**
 * @brief   set led status, in order to adapt data format, see details the file: snmp_custom.c 's snmpData[]
 * @param   val: 0 -> led off, 1 -> led on
 * @return  none
 */
void setUserLEDStatus(uint8_t val);

/* Network information to be configured. */
wiz_NetInfo net_info = {
    .mac = {0x00, 0x08, 0xdc, 0x1e, 0xed, 0x2e}, // Configured MAC address
    .ip = {192, 168, 1, 10},                     // Configured IP address
    .sn = {255, 255, 255, 0},                    // Configured subnet mask
    .gw = {192, 168, 1, 1},                      // Configured gateway
    .dns = {8, 8, 8, 8},                         // Configured domain address
    .dhcp = NETINFO_DHCP};                       // Configured dhcp model,NETINFO_DHCP:use dhcp; NETINFO_STATIC: use static ip.

static uint8_t ethernet_buf[ETHERNET_BUF_MAX_SIZE] = {
    0,
}; // Send and receive cache

static uint8_t breakout_flag = 0; // Define the DHCP acquisition flag
static uint16_t tcps_port = 8000;
static uint16_t udps_port = 5000;

#if (_WIZCHIP_ == W5100S)
static uint8_t tx_size[_WIZCHIP_SOCK_NUM_] = {4, 2, 2, 0};
static uint8_t rx_size[_WIZCHIP_SOCK_NUM_] = {4, 2, 2, 0};
#elif (_WIZCHIP_ == W5500)
static uint8_t tx_size[_WIZCHIP_SOCK_NUM_] = {4, 4, 2, 1, 1, 1, 1, 2};
static uint8_t rx_size[_WIZCHIP_SOCK_NUM_] = {4, 4, 2, 1, 1, 1, 1, 2};
#endif

int main()
{
    struct repeating_timer timer; // Define the timer structure
    wiz_NetInfo get_info;         // Stores the read configuration information

    /* MCU init */
    stdio_init_all();     // Initialize the main control peripheral
    wizchip_initialize(); // Initialize the chip interface

    /* socket rx and tx buff init */
    wizchip_init(tx_size, rx_size);
    wizchip_setnetinfo(&net_info); // Configure once first

    /* Onboard LED init*/
    UserLED_Init();

    /*dhcp init*/
    DHCP_init(SOCKET_ID, ethernet_buf);                                   // DHCP initialization
    add_repeating_timer_ms(1000, repeating_timer_callback, NULL, &timer); // Add DHCP 1s Tick Timer handler

    printf("wiznet chip upnp example.\r\n");
    network_init(&net_info);              // Configuring Network Information
    print_network_information(&get_info); // Read back the configuration information and print it

    do
    {
        printf("Send SSDP.. \r\n");
    } while (SSDPProcess(SOCKET_ID) != 0); // SSDP Search discovery

    if (GetDescriptionProcess(SOCKET_ID) == 0) // GET IGD description
    {
        printf("GetDescription Success!!\r\n");
    }
    else
    {
        printf("GetDescription Fail!!\r\n");
    }

    if (SetEventing(SOCKET_ID) == 0) // Subscribes IGD event messageS
    {
        printf("SetEventing Success!!\r\n");
    }
    else
    {
        printf("SetEventing Fail!!\r\n");
    }

    Main_Menu(SOCKET_ID, SOCKET_ID + 1, SOCKET_ID + 2, ethernet_buf, tcps_port, udps_port); // Main menu
}

void network_init(wiz_NetInfo *conf_info)
{
    int count = 0;
    uint8_t dhcp_retry = 0;

    if (conf_info->dhcp == NETINFO_DHCP)
    {
        while (true)
        {
            switch (DHCP_run()) // Do the DHCP client
            {
            case DHCP_IP_LEASED: // DHCP resolves the domain name successfully
            {
                if (breakout_flag == 0)
                {
                    printf("DHCP success\r\n");
                    getIPfromDHCP((*conf_info).ip);
                    getGWfromDHCP((*conf_info).gw);
                    getSNfromDHCP((*conf_info).sn);
                    getDNSfromDHCP((*conf_info).dns);
                    wizchip_setnetinfo(conf_info); // Configuring Network Information
                    close(SOCKET_ID);              // After dhcp close the socket, avoid errors in later use
                    breakout_flag = 1;
                }
                break;
            }
            case DHCP_FAILED:
            {
                printf(" DHCP failed \r\n");
                count++;
                if (count <= DHCP_RETRY_COUNT) // If the number of times is less than or equal to the maximum number of times, try again
                {
                    printf("DHCP timeout occurred and retry %d \r\n", count);
                }
                else if (count > DHCP_RETRY_COUNT) // If the number of times is greater than DHCP fails
                {
                    breakout_flag = 1; // if DHCP fail, use the static
                    DHCP_stop();       // Stop processing DHCP protocol
                    conf_info->dhcp = NETINFO_STATIC;
                    wizchip_setnetinfo(conf_info); // Configuring Network Information
                    break;
                }
                break;
            }
            }
            if (breakout_flag)
            {
                printf("config succ\r\n");
                break;
            }
        }
    }
    else
    {
        wizchip_setnetinfo(conf_info); // Configuring Network Information
    }
}

bool repeating_timer_callback(struct repeating_timer *t)
{
    DHCP_time_handler();         // DHCP 1s Tick Timer handler
    data_process_count_handle(); // UPNP 1s Tick Timer handler
    return true;
}

void UserLED_Init()
{
    gpio_init(USER_LED_PIN);              // Initialize LED
    gpio_set_dir(USER_LED_PIN, GPIO_OUT); // Output mode
    UserLED_Control_Init(setUserLEDStatus);
}

void setUserLEDStatus(uint8_t val)
{
    if (val == 0)
        gpio_put(USER_LED_PIN, 0);
    else
        gpio_put(USER_LED_PIN, 1);
}
